package nguyen.huu.phong.slidetext;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class Content {
	
	private List<File> files;
	private LinkedList<String> contents;
	private int current;
	private FilenameFilter filter;
	private Random random;
	
	public Content(String folder) throws IOException{
		files = new ArrayList<File>();
		contents = new LinkedList<String>();
		filter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				if (name.endsWith(".txt")){
					return true;
				} else {
					return false;
				}
			}
		};
		random = new Random();
		getFiles(folder);
		getContentOfFile();
	}
	
	public String getContent() throws IOException{
		if (!contents.isEmpty()){
			return contents.poll();
		} else if (!files.isEmpty()) {
			getContentOfFile();
			return getContent();
		} else {
			return "Vui lòng thêm dữ liệu tại " + new File(".").getAbsolutePath().replace(".", "") + " với định dạng .txt unicode";
		}
	}
	
	private void getContentOfFile() throws IOException{
		if (files.isEmpty()){
			return;
		} else if (current >= files.size()){
			current = 0;
		}
		File file = files.get(current++);
		BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-16"));
		contents.clear();
		while (true){
			String line = in.readLine();
			if (line == null) break;
			if (!line.trim().equals("")) contents.add(random.nextInt(contents.size() == 0 ? 1 : contents.size()), line);
		}
		if (contents.isEmpty()) files.remove(file);
	}
	
	private void getFiles(String folder){
		File dir = new File(folder);
		for (File file : dir.listFiles(filter)){
			files.add(random.nextInt(files.size() == 0 ? 1 : files.size()), file);
		}
	}

}
